from django.contrib.auth.models import Permission
from django.db.models import Q


def get_permission_names(user):
    """获取用户所有权限的 name 列表（去重）"""
    if user.is_superuser:
        return list(Permission.objects.values_list('name', flat=True))

    raw_permissions = user.get_all_permissions()  # 包含用户权限+组权限
    if not raw_permissions:
        return []

    # 解析 app_label 和 codename
    app_codenames = {}
    for perm in raw_permissions:
        app_label, codename = perm.split(".", 1)
        app_codenames.setdefault(app_label, []).append(codename)

    # 构建查询条件
    queries = Q()
    for app_label, codenames in app_codenames.items():
        queries |= Q(
            content_type__app_label=app_label,
            codename__in=codenames
        )

    # 查询并去重
    names = Permission.objects.filter(queries) \
        .values_list('name', flat=True) \
        .distinct()

    return list(names)
